package com.beiding.dbrequest.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.apache.dubbo.common.serialize.hessian2.Hessian2ObjectInput;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author 丁常磊
 * @date 2021/7/16 9:19
 */

public class HessianDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        list.add(new Hessian2ObjectInput(new InputStream() {
            @Override
            public int read() throws IOException {//不会调用
                return -1;
            }
            @Override
            public synchronized int read(byte b[], int off, int len) {
                int a = byteBuf.readableBytes();
                if (a >= len) {
                    byteBuf.readBytes(b, off, len);
                    return len;
                } else {
                    byteBuf.readBytes(b, off, a);
                    return a;
                }
            }
        }).readObject());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
